package etnorservice.etnor_service.utils;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: cc
 * @Date: 2024/11/25/11:43
 **/
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AesUtil {

    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String KEY = "1234567890123456"; // 16位的密钥
    private static final String IV = "1234567890123456";  // 16位的初始化向量

    /**
     * 加密方法
     * @param content 待加密的内容
     * @return 加密后的内容
     * @throws Exception 加密过程中可能出现的异常
     */
    public static String encrypt(String content) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encryptedBytes = cipher.doFinal(content.getBytes());
        return Base64.getUrlEncoder().encodeToString(encryptedBytes);
    }

    /**
     * 解密方法
     * @param content 待解密的内容
     * @return 解密后的内容
     * @throws Exception 解密过程中可能出现的异常
     */
    public static String decrypt(String content) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] decodedBytes = Base64.getUrlDecoder().decode(content);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes);
    }


}
